package com.cola;

import org.junit.jupiter.api.Test;

import java.nio.channels.Pipe;
import java.util.*;

/**
 * @Grup:com.cola
 * @Auther:cola
 * @Data:2021/4/8-2021-04-20:45
 * @version:1.0
 */
public class GenericDemo {

    public void test5() {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "cola");
        map.put(2, "tom");
        Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
        for (Map.Entry entry : entrySet) {
            System.out.println(entry.getKey() + "_" + entry.getValue());
        }
    }

    @Test
    public void test4() {
        String[] arrays = {"cola", "jacck", "tom"};
        String[] strs = func(arrays, 0, 1);
        System.out.println(Arrays.toString(strs));
    }

    /*
     *泛型方法
     * */
    public static <T> T[] func(T[] array, int i, int t) {
        T temp = array[i];
        array[i] = array[t];
        array[t] = temp;
        return array;
    }

    @Test
    public void test3() {
        Node<Number> n1 = new Node<>(14);
        Node<Integer> n2 = new Node<>(6);
        getData(n1);
        //getData(n2);//报错
        //n1==n2;//不支持
        getData2(n2);
        getData3(n1);
        getData3(n2);

    }

    /*
     * 无法转换
     * */
    public static void getData(Node<Number> node) {
        System.out.println(node.getData());
    }

    /*
     * 使用通配符定义泛型类型,此时只能输出,不能修改
     * */
    public static void getData2(Node<?> node) {
        System.out.println(node.getData());
    }

    public static void getData3(Node<? extends Number> node) {
        //只能是Number的子类和本身
        System.out.println(node.getData());
    }

    public static void getData4(Node<? super Number> node) {
        //只能是Number的父类和本身
        System.out.println(node.getData());
    }

    @Test
    public void testNode() {
        Node<String> stringNode = new Node<>("cola");
        Node<Integer> integerNode = new Node<>(10);
        System.out.println(stringNode.getData());
        System.out.println(integerNode.getData());

    }

    @Test
    public void test1() {
        List<String> list = new ArrayList<String>();
        list.add("cola");
        //list.add(45);
        //list.add(new Object());
        for (int i = 0; i < list.size(); i++) {
            //如果我们不能确定集合中的元素类型,那么我们需要再处理元素时
            //要判断元素的类型,才能做相应的操作

        }
    }
}
